package com.itheima.testservlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.itheima.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    //遍历
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //调用service层方法
        List<User> list = userService.findAll();
        ObjectMapper obj = new ObjectMapper();
        String str = obj.writeValueAsString(list);
        resp.getWriter().write(str);
    }
    //根据id删除元素
    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面传来的ids
        String ids = req.getParameter("ids");
        userService.deleteByIds(ids);
    }
    //新增
    //json方式
    /*private void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面传来的ids
        String userStr = req.getParameter("userstr");
        ObjectMapper obj = new ObjectMapper();
        User user = obj.readValue(userStr, User.class);
        System.out.println(user);
        userService.save(user);
    }*/
    private void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面传来的user
        BufferedReader reader = req.getReader();
        Gson gson = new Gson();
        User user = gson.fromJson(reader, User.class);
        userService.save(user);
    }
    //根据id查找
    private void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面传来的id
        String userId = req.getParameter("userid");
        System.out.println("-------------------"+userId);
        User user = userService.findById(userId);
        ObjectMapper obj = new ObjectMapper();
        String str = obj.writeValueAsString(user);
        resp.getWriter().write(str);
    }
    //更新
    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面传来的ids
        BufferedReader reader = req.getReader();
        Gson gson = new Gson();
        User user = gson.fromJson(reader, User.class);
        userService.update(user);
    }
}
